{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d124d22-de73-436b-86cd-9b162b469be8",
   "metadata": {
    "id": "2d124d22-de73-436b-86cd-9b162b469be8"
   },
   "outputs": [],
   "source": [
    "%pip install --upgrade pip\n",
    "\n",
    "# Uninstall conflicting packages\n",
    "%pip uninstall -y langchain-core langchain-openai langchain-experimental langchain-community langchain chromadb beautifulsoup4 python-dotenv PyPDF2 rank_bm25\n",
    "\n",
    "# Install compatible versions of langchain libraries\n",
    "%pip install langchain-core==0.3.6\n",
    "%pip install langchain-openai==0.2.1\n",
    "%pip install langchain-experimental==0.3.2\n",
    "%pip install langchain-community==0.3.1\n",
    "%pip install langchain==0.3.1\n",
    "\n",
    "# Install remaining packages\n",
    "%pip install chromadb==0.5.11\n",
    "%pip install beautifulsoup4==4.12.3\n",
    "%pip install python-dotenv==1.0.1\n",
    "%pip install PyPDF2==3.0.1 -q --user\n",
    "%pip install rank_bm25==0.2.2\n",
    "\n",
    "# Restart the kernel after installation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f884314f-870c-4bfb-b6c1-a5b4801ec172",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 4690,
     "status": "ok",
     "timestamp": 1716948148440,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "f884314f-870c-4bfb-b6c1-a5b4801ec172",
    "outputId": "76ea9fdd-5ba5-48f7-be31-351b68a76355"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['USER_AGENT'] = 'RAGUserAgent'\n",
    "import openai\n",
    "from langchain_openai import ChatOpenAI, OpenAIEmbeddings\n",
    "from langchain import hub\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain_core.runnables import RunnablePassthrough\n",
    "import chromadb\n",
    "from langchain_community.vectorstores import Chroma\n",
    "from langchain_core.runnables import RunnableParallel\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from PyPDF2 import PdfReader\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_core.documents.base import Document\n",
    "from langchain_community.retrievers import BM25Retriever\n",
    "from langchain.retrievers import EnsembleRetriever"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "eba3468a-d7c2-4a79-8df2-c335542950f2",
   "metadata": {
    "executionInfo": {
     "elapsed": 278,
     "status": "ok",
     "timestamp": 1716948177675,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "eba3468a-d7c2-4a79-8df2-c335542950f2"
   },
   "outputs": [],
   "source": [
    "# variables\n",
    "_ = load_dotenv(dotenv_path='env.txt')\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')\n",
    "openai.api_key = os.environ['OPENAI_API_KEY']\n",
    "llm = ChatOpenAI(model_name=\"gpt-4o-mini\", temperature=0)\n",
    "embedding_function = OpenAIEmbeddings()\n",
    "pdf_path = \"google-2023-environmental-report.pdf\"\n",
    "collection_name = \"google_environmental_report\"\n",
    "str_output_parser = StrOutputParser()\n",
    "user_query = \"What are Google's environmental initiatives?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "3a98dfb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "#### INDEXING ####"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "98ccda2c-0f4c-41c5-804d-2227cdf35aa7",
   "metadata": {
    "executionInfo": {
     "elapsed": 10611,
     "status": "ok",
     "timestamp": 1716948215859,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "98ccda2c-0f4c-41c5-804d-2227cdf35aa7"
   },
   "outputs": [],
   "source": [
    "# PDF Loader\n",
    "docs = []\n",
    "with open(pdf_path, \"rb\") as pdf_file:\n",
    "    pdf_reader = PdfReader(pdf_file)\n",
    "    pdf_text = \"\".join(page.extract_text() for page in pdf_reader.pages)\n",
    "    docs = [Document(page_content=page) for page in pdf_text.split(\"\\n\\n\")]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "855b6438-6c51-4b25-b799-36fb7b592bf5",
   "metadata": {
    "id": "855b6438-6c51-4b25-b799-36fb7b592bf5"
   },
   "outputs": [],
   "source": [
    "# RecursiveCharacterTextSplitter\n",
    "recursive_splitter = RecursiveCharacterTextSplitter(\n",
    "    separators=[\"\\n\\n\", \"\\n\", \". \", \" \", \"\"],\n",
    "    chunk_size=1000,\n",
    "    chunk_overlap=200\n",
    ")\n",
    "\n",
    "splits = recursive_splitter.split_documents(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d471eca-77dd-49b0-a61c-5b39019b56af",
   "metadata": {},
   "outputs": [],
   "source": [
    "dense_documents = [Document(page_content=doc.page_content, metadata={\"id\": str(i), \"search_source\": \"dense\"}) for i, doc in enumerate(splits)]\n",
    "sparse_documents = [Document(page_content=doc.page_content, metadata={\"id\": str(i), \"search_source\": \"sparse\"}) for i, doc in enumerate(splits)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6b13568c-d633-464d-8c43-0d55f34cc8c1",
   "metadata": {
    "executionInfo": {
     "elapsed": 4507,
     "status": "ok",
     "timestamp": 1716948724972,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "6b13568c-d633-464d-8c43-0d55f34cc8c1"
   },
   "outputs": [],
   "source": [
    "# Chroma Vector Store\n",
    "chroma_client = chromadb.Client()\n",
    "vectorstore = Chroma.from_documents(\n",
    "    documents=dense_documents,\n",
    "    embedding=embedding_function,\n",
    "    collection_name=collection_name,\n",
    "    client=chroma_client\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "749fcce7-3203-49e8-a62f-ecf2edce4570",
   "metadata": {
    "executionInfo": {
     "elapsed": 128,
     "status": "ok",
     "timestamp": 1716948726221,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "749fcce7-3203-49e8-a62f-ecf2edce4570"
   },
   "outputs": [],
   "source": [
    "dense_retriever = vectorstore.as_retriever(search_kwargs={\"k\": 10})\n",
    "sparse_retriever = BM25Retriever.from_documents(sparse_documents, k=10)\n",
    "ensemble_retriever = EnsembleRetriever(retrievers=[dense_retriever, sparse_retriever], weights=[0.5, 0.5], c=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6ce8df01-925b-45b5-8fb8-17b5c40c581f",
   "metadata": {
    "id": "6ce8df01-925b-45b5-8fb8-17b5c40c581f"
   },
   "outputs": [],
   "source": [
    "#### RETRIEVAL and GENERATION ####"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "fac053d8-b871-4b50-b04e-28dec9fb3b0f",
   "metadata": {
    "executionInfo": {
     "elapsed": 262,
     "status": "ok",
     "timestamp": 1716948727550,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "fac053d8-b871-4b50-b04e-28dec9fb3b0f"
   },
   "outputs": [],
   "source": [
    "# Prompt\n",
    "prompt = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    You are an environment expert assisting others in \n",
    "    understanding what large companies are doing to \n",
    "    improve the environment. Use the following pieces \n",
    "    of retrieved context with information about what \n",
    "    a particular company is doing to improve the \n",
    "    environment to answer the question. \n",
    "    \n",
    "    If you don't know the answer, just say that you don't know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: {context} \n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "5ef30632-13dd-4a34-af33-cb8fab94f169",
   "metadata": {
    "executionInfo": {
     "elapsed": 116,
     "status": "ok",
     "timestamp": 1716948728500,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "5ef30632-13dd-4a34-af33-cb8fab94f169"
   },
   "outputs": [],
   "source": [
    "# Relevance check prompt\n",
    "relevance_prompt_template = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Given the following question and retrieved context, determine if the context is relevant to the question.\n",
    "    Provide a score from 1 to 5, where 1 is not at all relevant and 5 is highly relevant.\n",
    "    Return ONLY the numeric score, without any additional text or explanation.\n",
    "\n",
    "    Question: {question}\n",
    "    Retrieved Context: {retrieved_context}\n",
    "\n",
    "    Relevance Score:\"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "e8975479-b3e3-481d-ad7b-08b4eb3faaef",
   "metadata": {
    "executionInfo": {
     "elapsed": 119,
     "status": "ok",
     "timestamp": 1716948730384,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "e8975479-b3e3-481d-ad7b-08b4eb3faaef"
   },
   "outputs": [],
   "source": [
    "# Post-processing\n",
    "def format_docs(docs):\n",
    "    return \"\\n\\n\".join(doc.page_content for doc in docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d6d7991f-24d0-47ea-b7ff-3ab2b8e12816",
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_score(llm_output):\n",
    "    try:\n",
    "        score = float(llm_output.strip())\n",
    "        return score\n",
    "    except ValueError:\n",
    "        return 0\n",
    "\n",
    "# Chain it all together with LangChain\n",
    "def conditional_answer(x):\n",
    "    relevance_score = extract_score(x['relevance_score'])\n",
    "    if relevance_score < 4:\n",
    "        return \"I don't know.\"\n",
    "    else:\n",
    "        return x['answer']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "07b9429a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate\n",
    "\n",
    "def augment_query_generated(user_query):\n",
    "    system_message_prompt = SystemMessagePromptTemplate.from_template(\n",
    "        \"You are a helpful expert environmental research assistant. Provide an example answer to the given question, that might be found in a document like an annual environmental report.\"\n",
    "    )\n",
    "    human_message_prompt = HumanMessagePromptTemplate.from_template(\"{query}\")\n",
    "    \n",
    "    chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])\n",
    "    \n",
    "    response = chat_prompt.format_prompt(query=user_query).to_messages()\n",
    "    \n",
    "    result = llm(response)\n",
    "    content = result.content\n",
    "    \n",
    "    return content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "7c7c43e7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "What are Google's environmental initiatives? In 2022, Google continued to advance its environmental initiatives, focusing on sustainability and reducing its carbon footprint. Key initiatives included:\n",
      "\n",
      "1. **Carbon Neutrality and Renewable Energy**: Google has maintained its carbon-neutral status since 2007 and aims to operate on 24/7 carbon-free energy by 2030. In 2022, Google procured over 7 gigawatts of renewable energy, making significant strides towards this goal.\n",
      "\n",
      "2. **Data Center Efficiency**: Google's data centers are among the most energy-efficient in the world. In 2022, the company achieved an average power usage effectiveness (PUE) of 1.10, significantly lower than the industry average. This was accomplished through advanced cooling technologies and AI-driven energy management systems.\n",
      "\n",
      "3. **Sustainable Products and Services**: Google has integrated sustainability into its product design and operations. The company launched new hardware products with recycled materials, and Google Cloud introduced tools to help businesses track and reduce their carbon emissions.\n",
      "\n",
      "4. **Circular Economy**: Google is committed to a circular economy, aiming to maximize the reuse of materials. In 2022, 50% of the materials used in Google’s products were recycled or renewable. Additionally, Google’s hardware recycling program expanded, allowing more consumers to return and recycle their old devices.\n",
      "\n",
      "5. **Water Stewardship**: Recognizing the importance of water conservation, Google implemented water stewardship programs across its data centers. In 2022, the company improved water efficiency by 20% through innovative cooling solutions and water recycling initiatives.\n",
      "\n",
      "6. **Biodiversity and Ecosystem Restoration**: Google invested in projects aimed at protecting and restoring biodiversity. This included partnerships with conservation organizations and the use of AI to monitor and protect endangered species and habitats.\n",
      "\n",
      "7. **Employee Engagement and Community Impact**: Google encouraged its employees to participate in sustainability initiatives through programs like the Google Green Team. The company also supported community projects focused on environmental education and local conservation efforts.\n",
      "\n",
      "These initiatives reflect Google’s commitment to sustainability and its role in addressing global environmental challenges. The company continues to innovate and collaborate to create a more sustainable future.\n"
     ]
    }
   ],
   "source": [
    "original_query = \"What are Google's environmental initiatives?\"\n",
    "hypothetical_answer = augment_query_generated(original_query)\n",
    "joint_query = f\"{original_query} {hypothetical_answer}\"\n",
    "print(joint_query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "4f372a3d-b323-4fd5-8f6d-3005684fc0eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "rag_chain_from_docs = (\n",
    "    RunnablePassthrough.assign(context=(lambda x: format_docs(x[\"context\"])))\n",
    "    | RunnableParallel(\n",
    "        {\n",
    "            \"relevance_score\": (\n",
    "                RunnablePassthrough()\n",
    "                | (lambda x: relevance_prompt_template.format(question=x['question'], retrieved_context=x['context']))\n",
    "                | llm\n",
    "                | str_output_parser\n",
    "            ), \n",
    "             \"answer\": (\n",
    "                RunnablePassthrough()\n",
    "                | prompt\n",
    "                | llm\n",
    "                | str_output_parser\n",
    "            )\n",
    "        }\n",
    "    )\n",
    "    | RunnablePassthrough().assign(final_answer=conditional_answer)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "6d69171d-c68e-412b-96fa-f681fd51c92f",
   "metadata": {},
   "outputs": [],
   "source": [
    "rag_chain_with_source = RunnableParallel(\n",
    "    {\"context\": ensemble_retriever, \"question\": RunnablePassthrough()}\n",
    ").assign(answer=rag_chain_from_docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "87cb96b1-3597-45c8-b6cc-d3eade50412d",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original Question: What are Google's environmental initiatives? In 2022, Google continued to advance its environmental initiatives, focusing on sustainability and reducing its carbon footprint. Key initiatives included:\n",
      "\n",
      "1. **Carbon Neutrality and Renewable Energy**: Google has maintained its carbon-neutral status since 2007 and aims to operate on 24/7 carbon-free energy by 2030. In 2022, Google procured over 7 gigawatts of renewable energy, making significant strides towards this goal.\n",
      "\n",
      "2. **Data Center Efficiency**: Google's data centers are among the most energy-efficient in the world. In 2022, the company achieved an average power usage effectiveness (PUE) of 1.10, significantly lower than the industry average. This was accomplished through advanced cooling technologies and AI-driven energy management systems.\n",
      "\n",
      "3. **Sustainable Products and Services**: Google has integrated sustainability into its product design and operations. The company launched new hardware products with recycled materials, and Google Cloud introduced tools to help businesses track and reduce their carbon emissions.\n",
      "\n",
      "4. **Circular Economy**: Google is committed to a circular economy, aiming to maximize the reuse of materials. In 2022, 50% of the materials used in Google’s products were recycled or renewable. Additionally, Google’s hardware recycling program expanded, allowing more consumers to return and recycle their old devices.\n",
      "\n",
      "5. **Water Stewardship**: Recognizing the importance of water conservation, Google implemented water stewardship programs across its data centers. In 2022, the company improved water efficiency by 20% through innovative cooling solutions and water recycling initiatives.\n",
      "\n",
      "6. **Biodiversity and Ecosystem Restoration**: Google invested in projects aimed at protecting and restoring biodiversity. This included partnerships with conservation organizations and the use of AI to monitor and protect endangered species and habitats.\n",
      "\n",
      "7. **Employee Engagement and Community Impact**: Google encouraged its employees to participate in sustainability initiatives through programs like the Google Green Team. The company also supported community projects focused on environmental education and local conservation efforts.\n",
      "\n",
      "These initiatives reflect Google’s commitment to sustainability and its role in addressing global environmental challenges. The company continues to innovate and collaborate to create a more sustainable future.\n",
      "\n",
      "Relevance Score: 5\n",
      "\n",
      "Final Answer:\n",
      "Google has implemented a comprehensive set of environmental initiatives aimed at sustainability and reducing its carbon footprint. Here are the key initiatives:\n",
      "\n",
      "1. **Carbon Neutrality and Renewable Energy**: Google has been carbon-neutral since 2007 and aims to operate on 24/7 carbon-free energy by 2030. In 2022, Google procured over 7 gigawatts of renewable energy.\n",
      "\n",
      "2. **Data Center Efficiency**: Google's data centers are among the most energy-efficient globally, achieving an average power usage effectiveness (PUE) of 1.10 in 2022. This was achieved through advanced cooling technologies and AI-driven energy management systems.\n",
      "\n",
      "3. **Sustainable Products and Services**: Google integrates sustainability into its product design and operations. In 2022, 50% of the materials used in Google’s products were recycled or renewable. Google Cloud also introduced tools to help businesses track and reduce their carbon emissions.\n",
      "\n",
      "4. **Circular Economy**: Google aims to maximize the reuse of materials. In 2022, 50% of the materials used in Google’s products were recycled or renewable. The company also expanded its hardware recycling program.\n",
      "\n",
      "5. **Water Stewardship**: Google implemented water stewardship programs across its data centers, improving water efficiency by 20% in 2022 through innovative cooling solutions and water recycling initiatives.\n",
      "\n",
      "6. **Biodiversity and Ecosystem Restoration**: Google invested in projects aimed at protecting and restoring biodiversity, including partnerships with conservation organizations and the use of AI to monitor and protect endangered species and habitats.\n",
      "\n",
      "7. **Employee Engagement and Community Impact**: Google encouraged its employees to participate in sustainability initiatives and supported community projects focused on environmental education and local conservation efforts.\n",
      "\n",
      "8. **Public Policy and Advocacy**: Google supports strong public policy action to create low-carbon economies and has been involved in various initiatives and partnerships to promote sustainability.\n",
      "\n",
      "9. **Supplier Engagement**: Google works with its suppliers to build an energy-efficient, low-carbon, circular supply chain, focusing on improving environmental performance and integrating sustainability principles.\n",
      "\n",
      "10. **Technological Innovations**: Google is investing in breakthrough technologies, such as next-generation geothermal power and battery-based backup power systems, to optimize the carbon footprint of its operations.\n",
      "\n",
      "These initiatives reflect Google’s commitment to sustainability and its role in addressing global environmental challenges. The company continues to innovate and collaborate to create a more sustainable future.\n",
      "\n",
      "\n",
      "Retrieved Documents:\n",
      "Document 1: Document ID: 117 source: dense\n",
      "Content:\n",
      "in four key ways: accelerating the transition to a net-zero carbon future, advancing water stewardship, building a circular economy, and protecting nature and biodiversity.Our \n",
      "operations\n",
      "Google uses energy, natural resources, and products \n",
      "and services to build our workplaces, data centers, and consumer hardware products. At the end of 2022, we had offices and data centers in roughly 200 cities  and nearly \n",
      "60 countries  around the world. We also had two retail \n",
      "stores, both in New York City.\n",
      "The products and services that our customers and users \n",
      "rely on—like Gmail, Google Cloud, Search, and YouTube—are powered by our data centers and networking infrastructure. At the end of 2022, we had 28 Google-owned and -operated data center campuses across 24 data center locations\n",
      " 65 on four continents, as well as more \n",
      "than 30 Google Cloud regions . In addition to our Google-\n",
      "owned and -operated data centers, we use additional third-party-operated data centers as well.\n",
      "\n",
      "Document 2: Document ID: 240 source: sparse\n",
      "Content:\n",
      "119 In 2020, we shared \n",
      "our next steps on this journey.\n",
      "We committed to   use recycled or renewable material in at \n",
      "least 50% of plastic  used across our consumer hardware \n",
      "product portfolio by 2025, prioritizing recycled plastic everywhere we can. 41% of the plastic Google used in products manufactured in 2022 was recycled content.\n",
      " 120\n",
      "Approximately 30% of the material Google used in its new products  launched and manufactured in 2022 was \n",
      "recycled content.\n",
      " 121 This includes recycled material used \n",
      "in our devices’ aluminum , stainless steel , rare-earth \n",
      "magnet , glass, and plastic  parts. \n",
      "2022 HIGHLIGHT\n",
      "The aluminum in the phone enclosures \n",
      "of Pixel 5, 6, 6 Pro, 7, and 7 Pro is made with 100% recycled content, reducing the carbon footprint of the aluminum portion of the enclosures by over 35% compared to 100% primary aluminum.\n",
      " 122 Using recycled materials can also lower the carbon\n",
      "\n",
      "Document 3: Document ID: 12 source: dense\n",
      "Content:\n",
      "The opportunity we have through our products and \n",
      "platforms is reflected in our updated environmental sustainability strategy, which focuses on where we can make the most significant positive impact. Our work is organized around three key pillars: empowering individuals to take action, working together with our partners and customers, and operating our business sustainably.\n",
      "In 2022, we reached our goal to help 1 billion people \n",
      "make more sustainable choices through our products. We achieved this by offering sustainability features like eco-friendly routing in Google Maps, energy efficiency features in Google Nest thermostats, and carbon emissions information in Google Flights. Looking ahead, our aspiration is to help individuals, cities, and other partners collectively reduce 1 gigaton of their carbon equivalent emissions annually by 2030.\n",
      " 2\n",
      "\n",
      "Document 4: Document ID: 337 source: sparse\n",
      "Content:\n",
      "and UN-Energy  to help grow the movement to enable zero-carbon electricity. In 2022, the compact surpassed \n",
      "100 signatories.\n",
      "Bonneville Environmental Foundation (BEF)Google has partnered closely with BEF since 2019 to kick off the implementation of our water strategy. In support of our 2030 replenishment and watershed health goals, it helped us to identify and support impactful water replenishment and watershed health projects globally, with a variety of local organizations and partners.\n",
      "Business for Social Responsibility (BSR) Google has been a member of BSR for many years and is one of a few select Spark members . We participate in \n",
      "a number of BSR collaboration initiatives, and one of our senior leaders sits on its board.\n",
      "C40 CitiesC40 and Google launched  the 24/7 Carbon-Free Energy for Cities program to empower cities around the world\n",
      "\n",
      "Document 5: Document ID: 13 source: dense\n",
      "Content:\n",
      "2\n",
      "After two years of condensed reporting, we’re sharing a deeper dive into our approach in one place in our 2023 Environmental Report. In 2022, we continued to make measurable progress in many key ways, such as:\n",
      "• We enhanced and launched new sustainabilityproduct features , such as eco-friendly routing in\n",
      "Maps, which is estimated to have helped preventmore than 1.2 million metric tons of carbon emissionsfrom launch through 2022—equivalent to takingapproximately 250,000 fuel-based cars off the roadfor a year.\n",
      " 3\n",
      "• We expanded the availability of Google EarthEngine —which provides access to reliable, up-to-\n",
      "date insights on how our planet is changing—toinclude businesses and governments worldwide as anenterprise-grade service through Google Cloud.• We opened our new Bay View campus , which is\n",
      "all-electric, net water-positive, restores over 17 acresof high-value nature, and incorporates the leadingprinciples of circular design.\n",
      "\n",
      "Document 6: Document ID: 239 source: sparse\n",
      "Content:\n",
      "We support greener electronics standards and \n",
      "certifications, including UL 110, IEEE 1680.1, and the UL ECOLOGO Program.\n",
      " 116\n",
      "The aluminum in the phone enclosures of Pixel 5, 6, 6 Pro, 7, and 7 Pro is made with 100% recycled content, reducing the carbon footprint of the aluminum portion of the enclosures by over 35% compared to 100% primary aluminum.\n",
      " 117   62\n",
      "2023 Environmental Report  Recycled materials \n",
      "Reducing how much waste we generate as a company and \n",
      "minimizing the demand for new raw materials starts with how we source materials that go into our products.\n",
      "In 2019, we announced our aim to include recycled \n",
      "materials in 100% of Google consumer hardware products launching in 2022 and every year after.\n",
      " 118 We hit our goal \n",
      "early—in 2020—and have maintained it each year since for Nest, Pixel, and Chromecast devices.\n",
      " 119 In 2020, we shared \n",
      "our next steps on this journey.\n",
      "We committed to   use recycled or renewable material in at\n",
      "\n",
      "Document 7: Document ID: 67 source: dense\n",
      "Content:\n",
      "Our approach\n",
      "Supporting partners\n",
      "Investing in breakthrough \n",
      "innovation\n",
      "Creating ecosystems for \n",
      "collaboration\n",
      "The journey ahead\n",
      "   21\n",
      "2023 Environmental Report  Our ambition\n",
      "We believe that Google has a unique \n",
      "opportunity that extends beyond reducing \n",
      "the environmental impacts of our own \n",
      "operations and value chain. By organizing \n",
      "information about our planet and making \n",
      "it actionable through technology and \n",
      "platforms, we can help partners and \n",
      "customers create even more positive impact.\n",
      "Digital technologies  play a critical role in industry \n",
      "transitions, allowing us to measure and track sustainability \n",
      "progress, optimize the use of resources, reduce \n",
      "greenhouse gas emissions, and enable a more circular \n",
      "economy. 50 Cloud computing and digital technologies \n",
      "underpin the transformation in many sectors, such as \n",
      "energy, transportation, and agriculture. Research  that \n",
      "we commissioned in 2022 found that 20%–25% of what’s \n",
      "required for the EU’s 2050 net-zero goal requires some\n",
      "\n",
      "Document 8: Document ID: 170 source: sparse\n",
      "Content:\n",
      "Both of these programs are based on discussions with  \n",
      "U.S. government officials, national NGOs, and policy advocates about challenges to an equitable energy transition in their communities. We’ll continue to build on these programs to extend the benefits of our investments to underserved communities.Accelerating new and \n",
      "improved technologies\n",
      "Wind and solar power have played a critical role in \n",
      "enabling Google’s clean energy progress, but meeting 24/7 CFE—and maximizing our contribution to global decarbonization—will require expanding our technology toolkit. In 2022, we continued to work on a wide range  of projects to demonstrate, scale, and maximize the climate impact of carbon-free energy technologies,  using Google’s engineering capabilities and purchasing demand to accelerate the commercialization of new  clean energy technologies:\n",
      " • Optimizing generation from existing CFE technologies: To reduce the carbon footprint of\n",
      "\n",
      "Document 9: Document ID: 172 source: dense\n",
      "Content:\n",
      "• Accelerating next generation energy sources:  \n",
      "In 2021, we signed the first corporate agreement to develop a next-generation geothermal  power project, \n",
      "and in 2022, we installed the first-ever battery-based backup  power system for a data center at our \n",
      "facility in St. Ghislain, Belgium. This application will enable Google to optimize the carbon footprint of backup power, buying local, low-carbon power for backup when available rather than relying on diesel generators.\n",
      " • Improving energy data and clean energy tracking: Google is driving the development of advanced methods for tracking clean energy, including time-based energy attribute certificates . We’re also working \n",
      "to improve the quality, consistency, and granularity of grid electricity data through active collaborations with organizations including EnergyTag, Electricity Maps, FlexiDAO, and more.We’re deploying machine learning solutions to optimize wind power forecasting  and project economics .\n",
      "\n",
      "Document 10: Document ID: 341 source: sparse\n",
      "Content:\n",
      "and to detect methane leaks in cities since 2011.\n",
      "European 24/7 HubGoogle supported the launch of the European 24/7 Hub with Eurelectric, which provides education on the  \n",
      "“what, why, and how” of 24/7 carbon-free energy buyers and suppliers in Europe. Google spoke at the  \n",
      "launch event during European Sustainable Energy Week.\n",
      "European Climate PactGoogle was among the leading businesses that joined the European Climate Pact in its inaugural year to share our commitment to help achieve a climate neutral Europe.\n",
      "European Green Digital Coalition (EGDC)Google is an active member of the EGDC—a group of technology companies committed to supporting the  \n",
      "green and digital transformation of the EU. As a member, Google participates in the initiative, designed to harness the emission-reducing potential of digital solutions for all other sectors, and support green and digital transformations in the EU.Organization Details\n",
      "\n",
      "Document 11: Document ID: 42 source: dense\n",
      "Content:\n",
      "that Google can make a meaningful difference beyond our own operations and value chain, and they highlight the benefits of helping individuals through our products and platforms.Our approach\n",
      "Every day, billions of people turn to Google to ask questions, discover something new, or learn about what’s important to them. More people are interested in how to live more sustainably than ever, and our aim is to make it easier for them to do so. In 2022, searches for   \n",
      "   “solar energy,”        “electric bicycles,”   and  \n",
      "   “electric cars”   reached all-time highs. 23 \n",
      "These kinds of changes to lifestyles and behavior matter: the International Energy Agency (IEA) estimates  that \n",
      "around 55% of the cumulative emissions reductions needed to achieve a net-zero global energy system by 2050 are linked to consumer choices. Yet, there’s a wide “say-do gap ” among consumers—between those who are \n",
      "concerned about sustainability, and those who ultimately make sustainable decisions.\n",
      " 24\n",
      "\n",
      "Document 12: Document ID: 108 source: sparse\n",
      "Content:\n",
      "Tidal testing its technology at a fish farm north of the Arctic Circle.   29\n",
      "2023 Environmental Report  Creating ecosystems for collaboration\n",
      "Beyond our own tools and programs, we continue to \n",
      "invest in promising initiatives that aim to create scalable, high-impact collaboration ecosystems for climate change and sustainability.\n",
      "Google.org\n",
      "Google.org  aims to bring the best of Google to help solve \n",
      "some of humanity’s biggest challenges. This includes combining funding, innovation, and technical expertise to support underserved communities, provide opportunity for everyone, and help address a number of sustainability challenges. \n",
      "Launched in 2022, the Google.org Impact Challenge on \n",
      "Climate Innovation  allocates up to $30 million to support \n",
      "breakthrough projects that use data and technology to accelerate climate action . Selected organizations will\n",
      "\n",
      "Document 13: Document ID: 4 source: dense\n",
      "Content:\n",
      "I worked on Search for 20 years, leading the product for \n",
      "many of those, and learned a lot about the unique impact Google can have on the world. I’ve always been proud of Google’s leadership in pushing the boundaries of sustainability in our data centers, including achieving carbon neutrality in 2007 (at the time, such accomplishments were uncommon). Going further, we’ve matched 100% of our global electricity use with renewable energy purchases for the last six years—a goal that seemed almost crazy when we set it in 2012. \n",
      "Today our ambitions have evolved—we now have a bold\n",
      "\n",
      "Document 14: Document ID: 70 source: sparse\n",
      "Content:\n",
      "intergovernmental organizations have leveraged and \n",
      "built upon our tools for a wide variety of use cases from \n",
      "measuring habitat ranges to protecting forest  and  \n",
      "ocean  ecosystems.\n",
      "Cloud\n",
      "Google Cloud is helping to transform  a number of carbon-\n",
      "emitting sectors, such as energy , transportation , and \n",
      "agriculture . We’ve made significant investments in cleaner \n",
      "cloud computing by making our data centers among the most efficient in the world and sourcing more carbon-free \n",
      "energy. This enables others to expand their use of digital \n",
      "technologies in a more sustainable way, by monitoring and \n",
      "optimizing cloud-related emissions, and choosing cleaner \n",
      "regions in which to run their workloads.\n",
      "AI\n",
      "As an AI-first company, we’ve established a track record of \n",
      "applying AI to some of the most significant challenges facing \n",
      "humanity, such as environmental degradation and climate change, and we see exciting opportunities for further \n",
      "impact. AI is embedded into many of our sustainability\n",
      "\n",
      "Document 15: Document ID: 311 source: dense\n",
      "Content:\n",
      "In 2022, we audited a subset of our suppliers to verify \n",
      "compliance for the following environmental criteria: implementation of environmental management systems, environmental permits and reporting, product content restrictions, and resource efficiency, as well as management of hazardous substances, wastewater,  solid waste, and air emissions.\n",
      "Googlers chat among indoor plants at our Pier 57 office in New York City.   79\n",
      "2023 Environmental Report  Public policy and advocacy\n",
      "We know that strong public policy action is critical to \n",
      "creating prosperous, equitable, and resilient low-carbon economies around the world. \n",
      "The United Nations Framework Convention on Climate \n",
      "Change (UNFCCC)’s 2015 Paris Agreement states that humanity must “keep global temperature rise this century well below 2°C above pre-industrial levels.”\n",
      " 143 Google\n",
      "\n",
      "Document 16: Document ID: 191 source: sparse\n",
      "Content:\n",
      "We’re working to achieve this replenishment target \n",
      "through continued and scaled investments in projects that are located within the watersheds we rely on to provide water to our data centers and offices. We work with external partners to implement these projects, which deliver both volumetric water benefits and improve other locally relevant aspects of watershed health, such as water quality, community water access, and biodiversity. Our approach\n",
      "At Google, we use water to help cool our data centers, and in our offices around the world. Water is also used throughout our value chain, in the manufacturing of both consumer hardware products and data center equipment.\n",
      "We work to drive water efficiency and reuse across our \n",
      "global operations, from reducing our potable water use intensity at our San Francisco Bay Area headquarters to using seawater for cooling at our data center in Hamina, Finland.\n",
      "Our water stewardship strategy  is centered on\n",
      "\n",
      "Document 17: Document ID: 116 source: dense\n",
      "Content:\n",
      "• Google Earth Engine\n",
      "• Sustainability-focused accelerators   31\n",
      "2023 Environmental Report  Operating \n",
      "sustainably\n",
      "We’re showing the way forward \n",
      "through our own operationsOur ambition\n",
      "Our operations\n",
      "Net-zero carbon\n",
      "Water stewardshipCircular economyNature and biodiversity\n",
      "Spotlight: Building a  \n",
      "more sustainable campus  \n",
      "in Mountain View\n",
      "   32\n",
      "2023 Environmental Report  Our  \n",
      "ambition\n",
      "Our work on sustainability started with our \n",
      "own operations, and we’ve worked hard to lead by example, with the ultimate goal of driving larger systems change. We set ambitious sustainability goals . We share the \n",
      "innovations we create and the lessons we learn with others, so we can help accelerate the global transition to a low-carbon and sustainable future.\n",
      "We’re working to drive sustainability across our operations \n",
      "in four key ways: accelerating the transition to a net-zero carbon future, advancing water stewardship, building a circular economy, and protecting nature and biodiversity.Our \n",
      "operations\n",
      "\n",
      "Document 18: Document ID: 308 source: sparse\n",
      "Content:\n",
      "on something outside of their primary role—related to sustainability. One great example of this is Project Sunroof, which began as a 20% project back in 2015. Lastly, employees have the opportunity to learn about sustainability through internal newsletters and education campaigns.\n",
      "Supplier \n",
      "engagement\n",
      "Through our supplier responsibility  program , we’re \n",
      "working to build an energy-efficient, low-carbon, \n",
      "circular supply chain that makes smart use of the Earth’s resources, protects ecosystems, and helps to combat climate change. We focus on the areas where we can make an immediate and lasting impact, such as helping our suppliers improve their environmental performance and integrate inclusivity, climate resilience, water stewardship, and circular design into our supply chain. We believe these principles can play a key role in reducing environmental impact and protecting human rights and community health.Google’s Supplier Code of Conduct includes requirements\n",
      "\n",
      "Document 19: Document ID: 179 source: dense\n",
      "Content:\n",
      "Google aims to enable 5 GW of new carbon-free \n",
      "energy through investments in our key manufacturing regions by 2030. In 2022, we signed agreements to invest approximately $350 million to support 0.5 GW of renewable energy projects towards this 5 GW total. This builds on our long-standing track record in this space; From 2010 to 2022, we entered into agreements to invest nearly $2.9 billion in renewable energy projects with an expected combined generation capacity of approximately 4.2 GW.\n",
      "Towards our 5 GW goal, Google’s investments will be \n",
      "targeted to support bringing additional carbon-free energy capacity online in key manufacturing regions around the globe, including in North America, Latin America, Europe, and Asia Pacific. Such projects may reduce Google’s carbon footprint directly, may reduce a Google supplier’s carbon footprint, or may simply help decarbonize the local grid.  \n",
      "Asia Pacific—a critical region for our suppliers—is one of\n",
      "\n",
      "Document 20: Document ID: 296 source: sparse\n",
      "Content:\n",
      "Alphabet’s Board of Directors has delegated to the Audit and Compliance Committee the primary responsibility for the oversight of many of the risks facing our businesses. The Audit and Compliance Committee reviews and discusses with management any major risk exposures, including sustainability risks, and the steps that Alphabet takes to detect, monitor, and actively manage such exposures.In 2022, Google evolved its approach to sustainability governance by creating a Sustainability Focus Area, an internal team led by our SVP of Learning and Sustainability that provides centralized management oversight of sustainability and climate-related issues.The Sustainability Focus Area includes the Chief Sustainability Officer and executives from across the company with diverse skills, from teams such as operations, products, finance, marketing, legal, communications, and policy, among others\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Query expansion with an answer RAG results\n",
    "result_alt = rag_chain_with_source.invoke(joint_query)\n",
    "retrieved_docs_alt = result_alt['context']\n",
    "\n",
    "print(f\"Original Question: {joint_query}\\n\")\n",
    "print(f\"Relevance Score: {result_alt['answer']['relevance_score']}\\n\")\n",
    "print(f\"Final Answer:\\n{result_alt['answer']['final_answer']}\\n\\n\")\n",
    "print(\"Retrieved Documents:\")\n",
    "for i, doc in enumerate(retrieved_docs_alt, start=1):\n",
    "    print(f\"Document {i}: Document ID: {doc.metadata['id']} source: {doc.metadata['search_source']}\")\n",
    "    print(f\"Content:\\n{doc.page_content}\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "a29e300f-dec7-4651-bdab-92afa4a9970b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "Google has implemented a comprehensive set of environmental initiatives aimed at sustainability and reducing its carbon footprint. Here are the key initiatives:\n",
       "\n",
       "1. **Carbon Neutrality and Renewable Energy**: Google has been carbon-neutral since 2007 and aims to operate on 24/7 carbon-free energy by 2030. In 2022, Google procured over 7 gigawatts of renewable energy.\n",
       "\n",
       "2. **Data Center Efficiency**: Google's data centers are among the most energy-efficient globally, achieving an average power usage effectiveness (PUE) of 1.10 in 2022. This was achieved through advanced cooling technologies and AI-driven energy management systems.\n",
       "\n",
       "3. **Sustainable Products and Services**: Google integrates sustainability into its product design and operations. In 2022, 50% of the materials used in Google’s products were recycled or renewable. Google Cloud also introduced tools to help businesses track and reduce their carbon emissions.\n",
       "\n",
       "4. **Circular Economy**: Google aims to maximize the reuse of materials. In 2022, 50% of the materials used in Google’s products were recycled or renewable. The company also expanded its hardware recycling program.\n",
       "\n",
       "5. **Water Stewardship**: Google implemented water stewardship programs across its data centers, improving water efficiency by 20% in 2022 through innovative cooling solutions and water recycling initiatives.\n",
       "\n",
       "6. **Biodiversity and Ecosystem Restoration**: Google invested in projects aimed at protecting and restoring biodiversity, including partnerships with conservation organizations and the use of AI to monitor and protect endangered species and habitats.\n",
       "\n",
       "7. **Employee Engagement and Community Impact**: Google encouraged its employees to participate in sustainability initiatives and supported community projects focused on environmental education and local conservation efforts.\n",
       "\n",
       "8. **Public Policy and Advocacy**: Google supports strong public policy action to create low-carbon economies and has been involved in various initiatives and partnerships to promote sustainability.\n",
       "\n",
       "9. **Supplier Engagement**: Google works with its suppliers to build an energy-efficient, low-carbon, circular supply chain, focusing on improving environmental performance and integrating sustainability principles.\n",
       "\n",
       "10. **Technological Innovations**: Google is investing in breakthrough technologies, such as next-generation geothermal power and battery-based backup power systems, to optimize the carbon footprint of its operations.\n",
       "\n",
       "These initiatives reflect Google’s commitment to sustainability and its role in addressing global environmental challenges. The company continues to innovate and collaborate to create a more sustainable future."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Markdown, display\n",
    "markdown_text_alt = result_alt['answer']['final_answer']\n",
    "display(Markdown(markdown_text_alt))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "ac8d4fef-04ca-426c-b742-a367818209ea",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original Question: What are Google's environmental initiatives?\n",
      "\n",
      "Relevance Score: 5\n",
      "\n",
      "Final Answer:\n",
      "Google has implemented a comprehensive environmental sustainability strategy organized around three key pillars: empowering individuals to take action, collaborating with partners and customers, and operating their business sustainably. Here are some of the specific initiatives and actions Google has taken to improve the environment:\n",
      "\n",
      "1. **Empowering Individuals:**\n",
      "   - **Sustainability Features in Products:** Google has integrated eco-friendly features into its products, such as eco-friendly routing in Google Maps, energy efficiency features in Google Nest thermostats, and carbon emissions information in Google Flights. In 2022, these efforts helped 1 billion people make more sustainable choices.\n",
      "   - **Future Goals:** Google aims to help individuals, cities, and partners collectively reduce 1 gigaton of carbon equivalent emissions annually by 2030.\n",
      "\n",
      "2. **Collaborating with Partners and Customers:**\n",
      "   - **Supplier Engagement:** Google works with its suppliers to reduce their energy consumption and greenhouse gas (GHG) emissions. This includes requiring suppliers to sign a Supplier Code of Conduct and assessing their practices through audits.\n",
      "   - **Industry Initiatives:** Google is a founding member of the iMasons Climate Accord, which focuses on carbon reduction in digital infrastructure. They also provided funding to ReFED to scale food waste solutions and supported The Nature Conservancy’s watershed and reforestation projects.\n",
      "   - **Public Policy and Advocacy:** Google engages in public policy to support low-carbon economies and has been involved in initiatives like the RE-Source Platform and the World Business Council for Sustainable Development (WBCSD).\n",
      "\n",
      "3. **Operating Sustainably:**\n",
      "   - **Data Centers:** Google has made its data centers some of the most efficient in the world, focusing on maximizing the efficient use of energy, water, and materials.\n",
      "   - **New Campuses:** The Bay View campus is all-electric, net water-positive, and incorporates principles of circular design.\n",
      "   - **Renewable Energy:** Google is investing in renewable energy projects and optimizing wind power output through predictive analytics.\n",
      "   - **Zero Waste:** Google aims to achieve UL 2799 Zero Waste to Landfill certification at all final assembly consumer hardware manufacturing sites by 2022.\n",
      "\n",
      "4. **Innovation and Technology:**\n",
      "   - **AI for Sustainability:** Google is leveraging artificial intelligence to help reduce emissions and improve sustainability practices.\n",
      "   - **Google Earth Engine:** This platform provides insights on planetary changes and is available to businesses and governments for sustainability efforts.\n",
      "   - **Google.org Impact Challenge on Climate Innovation:** This initiative supports projects that use data and technology to accelerate climate action.\n",
      "\n",
      "5. **Biodiversity and Nature Conservation:**\n",
      "   - **Campus Biodiversity:** Google strives to protect and enhance nature and biodiversity through its office and campus developments.\n",
      "   - **Community Engagement:** Google aims to make nature more accessible and protect it in the communities where it operates.\n",
      "\n",
      "These initiatives reflect Google's commitment to leveraging its technology and resources to make a significant positive impact on the environment.\n",
      "\n",
      "\n",
      "Retrieved Documents:\n",
      "Document 1: Document ID: 12 source: dense\n",
      "Content:\n",
      "The opportunity we have through our products and \n",
      "platforms is reflected in our updated environmental sustainability strategy, which focuses on where we can make the most significant positive impact. Our work is organized around three key pillars: empowering individuals to take action, working together with our partners and customers, and operating our business sustainably.\n",
      "In 2022, we reached our goal to help 1 billion people \n",
      "make more sustainable choices through our products. We achieved this by offering sustainability features like eco-friendly routing in Google Maps, energy efficiency features in Google Nest thermostats, and carbon emissions information in Google Flights. Looking ahead, our aspiration is to help individuals, cities, and other partners collectively reduce 1 gigaton of their carbon equivalent emissions annually by 2030.\n",
      " 2\n",
      "\n",
      "Document 2: Document ID: 150 source: sparse\n",
      "Content:\n",
      "sustainability, and we’re partnering with them to develop decarbonization roadmaps and build essential data infrastructure to accurately quantify emissions and reductions across the value chain.\n",
      "We engage with our suppliers—including hardware \n",
      "manufacturing and indirect services suppliers—to help reduce their energy consumption and GHG emissions, as stated in our Supplier Code of Conduct , which all \n",
      "suppliers are required to sign. We assess suppliers’ practices to report, manage, and reduce their emissions and incorporate this into our supplier scorecard.\n",
      "Reporting  \n",
      "environmental data\n",
      "We expect all our suppliers to report environmental data,\n",
      "\n",
      "Document 3: Document ID: 311 source: dense\n",
      "Content:\n",
      "In 2022, we audited a subset of our suppliers to verify \n",
      "compliance for the following environmental criteria: implementation of environmental management systems, environmental permits and reporting, product content restrictions, and resource efficiency, as well as management of hazardous substances, wastewater,  solid waste, and air emissions.\n",
      "Googlers chat among indoor plants at our Pier 57 office in New York City.   79\n",
      "2023 Environmental Report  Public policy and advocacy\n",
      "We know that strong public policy action is critical to \n",
      "creating prosperous, equitable, and resilient low-carbon economies around the world. \n",
      "The United Nations Framework Convention on Climate \n",
      "Change (UNFCCC)’s 2015 Paris Agreement states that humanity must “keep global temperature rise this century well below 2°C above pre-industrial levels.”\n",
      " 143 Google\n",
      "\n",
      "Document 4: Document ID: 309 source: sparse\n",
      "Content:\n",
      "that enable us to ensure that those we partner with are responsible environmental stewards. Along with having suppliers evaluate their operations, we perform our own ongoing due diligence and audits to verify compliance and to understand our supply chain’s current and potential risks.\n",
      "When we find that a supplier isn’t complying, we expect\n",
      "\n",
      "Document 5: Document ID: 344 source: dense\n",
      "Content:\n",
      "iMasons Climate AccordGoogle is a founding member and part of the governing body of the iMasons Climate Accord, a coalition united on carbon reduction in digital infrastructure.\n",
      "ReFEDIn 2022, to activate industry-wide change, Google provided anchor funding to kickstart the ReFED Catalytic Grant Fund, with the goal of accelerating and scaling food waste solutions.\n",
      "The Nature Conservancy (TNC)In 2022, Google supported three of the Nature Conservancy’s watershed projects in Chile and the United States, and Google.org supported a three-phased approach to catalyze active reforestation of kelp at impactful scales. Google.org also provided a grant to TNC to develop a machine-learning-powered timber-tracing API to stop deforestation in the Amazon at scale; a team of Google engineers is working full-time for six months with TNC to develop this product as part of the Google.org Fellowship Program.\n",
      "\n",
      "Document 6: Document ID: 298 source: sparse\n",
      "Content:\n",
      "2023 Environmental Report  Risk management\n",
      "Our Enterprise Risk Management (ERM) team is responsible \n",
      "for identifying, assessing, and reporting risks related to the company’s operations, financial performance, and reputation. As with financial, operational, and strategic risks, the team assesses environmental risks as part of the company’s overall risk management framework. The risks and opportunities identified through this process support public disclosures and inform Google’s environmental sustainability strategy. Our Chief Sustainability Officer and sustainability teams work to address risks by identifying opportunities to reduce the company’s environmental impacts from its operations and value chain, and through improving climate resilience. \n",
      "Climate-related \n",
      "risks\n",
      "Climate-related risks and opportunities have long time\n",
      "\n",
      "Document 7: Document ID: 13 source: dense\n",
      "Content:\n",
      "2\n",
      "After two years of condensed reporting, we’re sharing a deeper dive into our approach in one place in our 2023 Environmental Report. In 2022, we continued to make measurable progress in many key ways, such as:\n",
      "• We enhanced and launched new sustainabilityproduct features , such as eco-friendly routing in\n",
      "Maps, which is estimated to have helped preventmore than 1.2 million metric tons of carbon emissionsfrom launch through 2022—equivalent to takingapproximately 250,000 fuel-based cars off the roadfor a year.\n",
      " 3\n",
      "• We expanded the availability of Google EarthEngine —which provides access to reliable, up-to-\n",
      "date insights on how our planet is changing—toinclude businesses and governments worldwide as anenterprise-grade service through Google Cloud.• We opened our new Bay View campus , which is\n",
      "all-electric, net water-positive, restores over 17 acresof high-value nature, and incorporates the leadingprinciples of circular design.\n",
      "\n",
      "Document 8: Document ID: 115 source: dense\n",
      "Content:\n",
      "of over 140 partner organizations.\n",
      "The Google.org Impact Challenge on Climate Innovation supports breakthrough projects that use data and technology to \n",
      "accelerate climate action.\n",
      "The journey ahead\n",
      "From measuring and monitoring changes on the Earth’s surface, improving forecast and prediction models for flooding and wildfires, optimizing operations, combining disparate data sources, and designing more efficient products, we continue to leverage our expertise in technology and apply the latest advancements to help solve global challenges.\n",
      "We believe that by working together with our partners and \n",
      "customers, we can make a real difference in addressing the challenges of climate change and ecosystem degradation. LEARN MORE\n",
      "• Data Commons\n",
      "• Environmental Insights Explorer\n",
      "• Google Cloud sustainability\n",
      "• Google Earth Engine\n",
      "• Sustainability-focused accelerators   31\n",
      "2023 Environmental Report  Operating \n",
      "sustainably\n",
      "We’re showing the way forward \n",
      "through our own operationsOur ambition\n",
      "\n",
      "Document 9: Document ID: 328 source: sparse\n",
      "Content:\n",
      "Sustainable \n",
      "consumption of \n",
      "public goods (e.g., \n",
      "“right to repair”)Google submitted comments to the European Commission’s public consultation regarding \n",
      "the promotion of repair and reuse of goods. We shared our views on the core principles to \n",
      "consider when introducing policy measures to promote repair and reuse horizontally, and for \n",
      "smartphones and tablets specifically.\n",
      "Body of European \n",
      "Regulators \n",
      "for Electronic \n",
      "Communications \n",
      "(BEREC)Google responded to a questionnaire  by BEREC in view of the development of key performance \n",
      "indicators to characterize the environmental impact of electronic communications, networks, \n",
      "devices, and services. We provided information about our environmental reporting practices \n",
      "and suggestions to help identify which indicators would provide relevant environmental \n",
      "information.\n",
      "Engagement with coalitions and sustainability initiatives\n",
      "RE-Source PlatformGoogle is a strategic partner and steering committee member of the RE-Source Platform, the\n",
      "\n",
      "Document 10: Document ID: 67 source: dense\n",
      "Content:\n",
      "Our approach\n",
      "Supporting partners\n",
      "Investing in breakthrough \n",
      "innovation\n",
      "Creating ecosystems for \n",
      "collaboration\n",
      "The journey ahead\n",
      "   21\n",
      "2023 Environmental Report  Our ambition\n",
      "We believe that Google has a unique \n",
      "opportunity that extends beyond reducing \n",
      "the environmental impacts of our own \n",
      "operations and value chain. By organizing \n",
      "information about our planet and making \n",
      "it actionable through technology and \n",
      "platforms, we can help partners and \n",
      "customers create even more positive impact.\n",
      "Digital technologies  play a critical role in industry \n",
      "transitions, allowing us to measure and track sustainability \n",
      "progress, optimize the use of resources, reduce \n",
      "greenhouse gas emissions, and enable a more circular \n",
      "economy. 50 Cloud computing and digital technologies \n",
      "underpin the transformation in many sectors, such as \n",
      "energy, transportation, and agriculture. Research  that \n",
      "we commissioned in 2022 found that 20%–25% of what’s \n",
      "required for the EU’s 2050 net-zero goal requires some\n",
      "\n",
      "Document 11: Document ID: 415 source: sparse\n",
      "Content:\n",
      "chemistry\n",
      "• Governance and engagement - Risk management; Stakeholder engagement - Supplier \n",
      "engagement\n",
      "Engagement with external targets and initiatives related to sustainable \n",
      "supply chains • Wor king together - Our approach - Supporting partners - Cloud customers and  \n",
      "commercial partners\n",
      "• Governance and engagement - PartnershipsC12. Engagement\n",
      "Goals and targets Supplier environmental assessment-related targets• Introd uction - Targets and progress summary\n",
      "• Oper ating sustainably - Circular economy - Our approach - Working with suppliers\n",
      "Performance indicators New suppliers that were screened using environmental criteria • Governance and engagement - Risk management C12. Engagement\n",
      "Supplier renewable energy• Opera ting sustainably - Net-zero carbon - Our approach - Advancing carbon-free energy - \n",
      "CFE inv estmentsC2. Risks and opportunities\n",
      "Negative environmental impacts in the supply chain and actions taken• Oper ating sustainably - Circular economy - Supply chain\n",
      "\n",
      "Document 12: Document ID: 346 source: dense\n",
      "Content:\n",
      "World Business Council for Sustainable Development (WBCSD)Google has been a member of the WBCSD for several years and participates in a number of its initiatives. \n",
      "We’re a\n",
      "ctively involved in initiatives related to improving well-being for people and the planet, including  \n",
      "shifting diets, consumer behavior changes, and regenerative agriculture. \n",
      "World Resources Institute (WRI)Google has a 13-year long relationship with WRI for impact-focused collaboration. Some key projects include developing a near-real-time land cover dataset ( Dynamic World ), deforestation monitoring and alerts ( Global \n",
      "Forest Watch ), ending commodity-driven deforestation and accelerating restoration ( Forest Data Partnership ), \n",
      "measuring and mitigating extreme heat ( supported by Google.org ), and educating stakeholders on 24/7 CFE.   84\n",
      "2023 Environmental Report  Awards and recognition\n",
      "2022 CDP Climate Change A List  \n",
      "Alphabet has been named to CDP’s Climate Change A list,\n",
      "\n",
      "Document 13: Document ID: 139 source: sparse\n",
      "Content:\n",
      "development and deployment of these materials.\n",
      "In 2022, we filed a patent for using machine \n",
      "learning technology to improve our ability to prevent emissions from refrigerant leaks.\n",
      "Data centers\n",
      "Google’s data centers are the engine of our company, powering products like Gmail, Google Cloud, Search, and YouTube for billions of people around the world. We’ve worked to make Google’s data centers some of the most efficient in the world, improving their environmental performance even as demand for our products has risen. We’ve done this by designing, building, and operating each one to maximize efficient use of energy, water, \n",
      "and ma\n",
      "terials.\n",
      "Our long-standing data center efficiency  efforts are\n",
      "\n",
      "Document 14: Document ID: 111 source: dense\n",
      "Content:\n",
      "Googlers collaborate in the Event Center at our Bay View campus.   30\n",
      "2023 Environmental Report  Google for Startups\n",
      "By investing early in technologies aimed at tackling \n",
      "sustainability challenges like climate change, we have the potential to move the needle on sustainability and positively impact our planet. We have a portfolio of sustainability-focused accelerators , which support  \n",
      "early stage innovations to grow and scale.\n",
      "Google for Startups \n",
      "Accelerator\n",
      "Google for Startups is working to identify, support, and\n",
      "\n",
      "Document 15: Document ID: 432 source: sparse\n",
      "Content:\n",
      "2023 Environmental Report  market structures. If no such structure exists, then Google defines the grid \n",
      "region as the electricity-balancing authority where our data centers are \n",
      "located. Outside of the United States, the grid region most often refers to \n",
      "the geographic boundary of a country, because most grid system operators \n",
      "operate at the national level. Certain regions that span multiple countries \n",
      "are well interconnected and could be considered as one grid; however, \n",
      "our grid mix calculations already include import and export considerations \n",
      "and therefore take into account power flows from neighboring grids. In \n",
      "the future, we may update our definition as we work with grid operators to \n",
      "better understand how transmission constraints or congestion impact CFE \n",
      "measurement within and across grid regions.\n",
      "91 Contracted CFE is the hourly electricity production from clean energy \n",
      "projects whose electricity and associated environmental attributes are\n",
      "\n",
      "Document 16: Document ID: 66 source: dense\n",
      "Content:\n",
      "the United States for pre-owned products, such as used and refurbished products. The journey \n",
      "ahead\n",
      "While a single individual’s actions may seem small, when \n",
      "billions of people have the tools to make more sustainable decisions, they add up to have a meaningful impact on their communities and the entire planet. \n",
      "We’re excited by the opportunity to enable climate and \n",
      "environmental action far beyond Google’s direct impact, through information and innovation.\n",
      "LEARN MORE\n",
      " • Empowering with technology\n",
      " • Google Maps eco-friendly routing\n",
      " • Searching for sustainability with Google\n",
      " • Supporting a clean energy future with Nest Renew\n",
      " • The search for sustainability   20\n",
      "2023 Environmental Report  Working \n",
      "together\n",
      "We’re working together with our \n",
      "partners and customers to advance technology for sustainabilityOur ambition\n",
      "Our approach\n",
      "Supporting partners\n",
      "Investing in breakthrough \n",
      "innovation\n",
      "Creating ecosystems for \n",
      "collaboration\n",
      "The journey ahead\n",
      "   21\n",
      "2023 Environmental Report  Our ambition\n",
      "\n",
      "Document 17: Document ID: 91 source: sparse\n",
      "Content:\n",
      "EV Suitability Assessment helps organizations monitor their fleet of vehicles and make choices that minimize environmental impact.\n",
      "Data analytics tools from Google Cloud are also helping \n",
      "airlines. Lufthansa Group partnered with Google Cloud \n",
      "and Google Research to develop a platform that facilitates better planning and management of daily flight operations.\n",
      "We’re helping organizations harness \n",
      "the power of data and AI to drive more intelligent supply chains.Renewable energy\n",
      "Wind farms are an important source of carbon-free electricity, but wind can fluctuate depending on the weather. Through Google Cloud, customers like Engie  (a global energy and renewables supplier) can optimize their wind portfolio in short-term power markets by predicting wind power output 36 hours ahead of actual generation  and making optimal hourly delivery \n",
      "commitments to the grid, a full day in advance.  \n",
      "Sustainability partner \n",
      "solutions\n",
      "Partner solutions are important to scale the impact for our\n",
      "\n",
      "Document 18: Document ID: 262 source: dense\n",
      "Content:\n",
      "135 \n",
      "Preserving nature is critical both to mitigating climate  \n",
      "change and adapting to it. We want nature and people to flourish together in the communities that Google calls  home, as well as the ecosystems where we source food  for the hundreds of cafes we operate. Our approach\n",
      "We strive to protect and enhance nature and biodiversity through our campuses and technology.\n",
      "Google has offices in nearly 60 countries around the world \n",
      "(as of year-end 2022). In these locations, we aim to protect and enhance nature and biodiversity through a four-pillar approach that starts with building biodiversity at our own office and campus developments, as well as protecting nature and making it more accessible in the surrounding communities where we operate (see Figure 24). \n",
      "Our approach further focuses on sourcing responsibly\n",
      "\n",
      "Document 19: Document ID: 22 source: sparse\n",
      "Content:\n",
      "cled/ Ongoing  36% 41% 2025our consumer hardware product portfolio by 2025 renewable material (see pg. 62 )\n",
      "% plastic-free Ongoing  Make product packaging 100% plastic-free by 2025 97% 96% 2025packaging (see pg. 63 )\n",
      "Significant  Achieve UL 2799 Zero Waste to Landfill certification at all final \n",
      "Supply chain % of sites certified 9% 90% 2022 progress  assembly consumer hardware manufacturing sites by 2022\n",
      "(see pg. 65 )   9\n",
      "2023 Environmental Report  \n",
      "Emerging opportunities\n",
      "As the world becomes increasingly aware of the need for sustainability, individuals, businesses, and communities are  \n",
      "looking for new ways to reduce their environmental impact. Artificial intelligence (AI) and the power of information to help individuals and organizations reduce emissions are two emerging opportunities that Google is focusing on to help build a more sustainable future.\n",
      "AI for sustainability\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Hybrid RAG results\n",
    "result = rag_chain_with_source.invoke(user_query)\n",
    "retrieved_docs = result['context']\n",
    "\n",
    "print(f\"Original Question: {user_query}\\n\")\n",
    "print(f\"Relevance Score: {result['answer']['relevance_score']}\\n\")\n",
    "print(f\"Final Answer:\\n{result['answer']['final_answer']}\\n\\n\")\n",
    "print(\"Retrieved Documents:\")\n",
    "for i, doc in enumerate(retrieved_docs, start=1):\n",
    "    print(f\"Document {i}: Document ID: {doc.metadata['id']} source: {doc.metadata['search_source']}\")\n",
    "    print(f\"Content:\\n{doc.page_content}\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "64cfbbc9-0f9a-43f2-a9f0-4f5bd3612a3f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "Google has implemented a comprehensive environmental sustainability strategy organized around three key pillars: empowering individuals to take action, collaborating with partners and customers, and operating their business sustainably. Here are some of the specific initiatives and actions Google has taken to improve the environment:\n",
       "\n",
       "1. **Empowering Individuals:**\n",
       "   - **Sustainability Features in Products:** Google has integrated eco-friendly features into its products, such as eco-friendly routing in Google Maps, energy efficiency features in Google Nest thermostats, and carbon emissions information in Google Flights. In 2022, these efforts helped 1 billion people make more sustainable choices.\n",
       "   - **Future Goals:** Google aims to help individuals, cities, and partners collectively reduce 1 gigaton of carbon equivalent emissions annually by 2030.\n",
       "\n",
       "2. **Collaborating with Partners and Customers:**\n",
       "   - **Supplier Engagement:** Google works with its suppliers to reduce their energy consumption and greenhouse gas (GHG) emissions. This includes requiring suppliers to sign a Supplier Code of Conduct and assessing their practices through audits.\n",
       "   - **Industry Initiatives:** Google is a founding member of the iMasons Climate Accord, which focuses on carbon reduction in digital infrastructure. They also provided funding to ReFED to scale food waste solutions and supported The Nature Conservancy’s watershed and reforestation projects.\n",
       "   - **Public Policy and Advocacy:** Google engages in public policy to support low-carbon economies and has been involved in initiatives like the RE-Source Platform and the World Business Council for Sustainable Development (WBCSD).\n",
       "\n",
       "3. **Operating Sustainably:**\n",
       "   - **Data Centers:** Google has made its data centers some of the most efficient in the world, focusing on maximizing the efficient use of energy, water, and materials.\n",
       "   - **New Campuses:** The Bay View campus is all-electric, net water-positive, and incorporates principles of circular design.\n",
       "   - **Renewable Energy:** Google is investing in renewable energy projects and optimizing wind power output through predictive analytics.\n",
       "   - **Zero Waste:** Google aims to achieve UL 2799 Zero Waste to Landfill certification at all final assembly consumer hardware manufacturing sites by 2022.\n",
       "\n",
       "4. **Innovation and Technology:**\n",
       "   - **AI for Sustainability:** Google is leveraging artificial intelligence to help reduce emissions and improve sustainability practices.\n",
       "   - **Google Earth Engine:** This platform provides insights on planetary changes and is available to businesses and governments for sustainability efforts.\n",
       "   - **Google.org Impact Challenge on Climate Innovation:** This initiative supports projects that use data and technology to accelerate climate action.\n",
       "\n",
       "5. **Biodiversity and Nature Conservation:**\n",
       "   - **Campus Biodiversity:** Google strives to protect and enhance nature and biodiversity through its office and campus developments.\n",
       "   - **Community Engagement:** Google aims to make nature more accessible and protect it in the communities where it operates.\n",
       "\n",
       "These initiatives reflect Google's commitment to leveraging its technology and resources to make a significant positive impact on the environment."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Markdown, display\n",
    "markdown_text = result['answer']['final_answer']\n",
    "display(Markdown(markdown_text))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7268a590-7c7f-44d2-ad9b-e1a5e6ec1e4e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "name": "CHAPTER11-2_TEXT_SPLITTERS.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  },
  "vscode": {
   "interpreter": {
    "hash": "e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
